<template>
  <div class="page-container">
    <el-card v-if="event">
      <template #header>
        <div class="card-header">
          <h3>运行事件: {{ event.name }}</h3>
          <div>
            <el-button @click="goBack">返回详情</el-button>
            <el-button type="primary" @click="runEvent" :disabled="running">
              {{ running ? '运行中...' : '重新运行' }}
            </el-button>
          </div>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card class="run-card">
            <template #header>
              <div class="card-header">
                <h4>运行日志</h4>
                <el-button size="small" @click="clearLogs" :disabled="running">清空日志</el-button>
              </div>
            </template>
            <div class="log-container" ref="logContainer">
              <div v-if="logs.length > 0">
                <div v-for="(log, index) in logs" :key="index" :class="['log-item', log.type]">
                  {{ log.message }}
                </div>
              </div>
              <div v-else class="empty-log">
                <p>暂无日志，请点击运行按钮开始执行事件</p>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card v-if="currentInteraction" class="interaction-card">
            <template #header>
              <div class="card-header">
                <h4>用户交互 <el-tag size="small" effect="dark" type="warning">{{ currentInteraction.type === 'input' ? '输入' : (currentInteraction.type === 'branch' ? '分支选择' : '选择') }}</el-tag></h4>
              </div>
            </template>
            <div class="interaction-container">
              <p class="interaction-prompt">{{ currentInteraction.prompt }}</p>
              
              <!-- 文本输入交互 -->
              <template v-if="currentInteraction.type === 'input'">
                <el-input 
                  v-model="interactionResponse" 
                  :placeholder="currentInteraction.placeholder || '请输入'" 
                  @keyup.enter="submitInteraction"
                  class="interaction-input"
                  autofocus
                ></el-input>
                <el-button type="primary" @click="submitInteraction" style="margin-top: 10px;">
                  提交
                </el-button>
              </template>
              
              <!-- 选择交互 -->
              <template v-if="currentInteraction.type === 'select'">
                <el-radio-group v-model="interactionResponse" class="interaction-options">
                  <el-radio 
                    v-for="option in currentInteraction.options" 
                    :key="option.value" 
                    :label="option.value"
                    class="interaction-option"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
                <div>
                  <el-button type="primary" @click="submitInteraction" style="margin-top: 10px;">
                    提交
                  </el-button>
                </div>
              </template>
              
              <!-- 分支选择交互 -->
              <template v-if="currentInteraction.type === 'branch'">
                <el-radio-group v-model="interactionResponse" class="interaction-options branch-options">
                  <el-radio 
                    v-for="option in currentInteraction.options" 
                    :key="option.value" 
                    :label="option.value"
                    class="interaction-option branch-option"
                  >
                    {{ option.label }}
                  </el-radio>
                </el-radio-group>
                <div>
                  <el-button type="primary" @click="submitInteraction" style="margin-top: 10px;">
                    继续此分支
                  </el-button>
                </div>
              </template>
              
              <!-- 调试信息 -->
              <div v-if="isDev" class="debug-info">
                <el-divider>调试信息</el-divider>
                <pre>{{ JSON.stringify(currentInteraction, null, 2) }}</pre>
              </div>
            </div>
          </el-card>
          <el-alert
            v-else-if="running && !eventFinished"
            title="事件正在执行中，无需用户输入"
            type="info"
            :closable="false"
            style="margin-bottom: 20px;"
          />
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card class="variables-card">
            <template #header>
              <div class="card-header">
                <h4>运行时变量</h4>
              </div>
            </template>
            <div v-if="Object.keys(variables).length > 0">
              <el-descriptions :column="2" border>
                <el-descriptions-item v-for="(value, key) in variables" :key="key" :label="key">
                  {{ typeof value === 'object' ? JSON.stringify(value) : value }}
                </el-descriptions-item>
              </el-descriptions>
            </div>
            <el-empty v-else description="暂无变量数据" />
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    
    <el-skeleton v-else :rows="10" animated />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const store = useStore()
const router = useRouter()
const route = useRoute()

const logContainer = ref(null)
const currentInteraction = ref(null)
const interactionResponse = ref('')
const variables = ref({})
const currentNodeIndex = ref(0)
const eventFinished = ref(false)

const running = computed(() => store.state.running)
const logs = computed(() => store.state.logs)
const event = computed(() => store.state.currentEvent)
const isDev = computed(() => import.meta.env.DEV)

// 滚动日志到底部
watch(logs, () => {
  nextTick(() => {
    if (logContainer.value) {
      logContainer.value.scrollTop = logContainer.value.scrollHeight
    }
  })
})

const fetchEvent = async () => {
  try {
    await store.dispatch('fetchEventById', route.params.id)
  } catch (error) {
    ElMessage.error('获取事件详情失败')
  }
}

const goBack = () => {
  router.push(`/events/${route.params.id}`)
}

const clearLogs = () => {
  store.commit('CLEAR_LOGS')
}

const runEvent = async () => {
  // 重置状态
  store.commit('CLEAR_LOGS')
  variables.value = {}
  currentNodeIndex.value = 0
  eventFinished.value = false
  currentInteraction.value = null
  
  // 添加开始日志
  store.commit('ADD_LOG', {
    type: 'info',
    message: `开始运行事件: ${event.value.name}`,
    timestamp: new Date().toISOString()
  })
  
  // 设置运行状态
  store.commit('SET_RUNNING', true)
  
  // 确保事件有节点
  if (!event.value.nodes || event.value.nodes.length === 0) {
    store.commit('ADD_LOG', {
      type: 'error',
      message: '事件没有节点，无法运行',
      timestamp: new Date().toISOString()
    })
    
    // 保存错误日志
    await saveErrorLog('事件没有节点，无法运行')
    return
  }
  
  // 开始执行第一个节点
  processNextNode()
}

const processNextNode = () => {
  if (eventFinished.value || !running.value) return
  
  if (currentNodeIndex.value >= event.value.nodes.length) {
    finishEvent()
    return
  }
  
  const node = event.value.nodes[currentNodeIndex.value]
  
  store.commit('ADD_LOG', {
    type: 'info',
    message: `执行节点: ${node.name} (类型: ${node.type})`,
    timestamp: new Date().toISOString()
  })
  
  // 根据节点类型处理
  switch (node.type) {
    case 'start':
      processStart(node)
      break
    case 'end':
      processEnd(node)
      break
    case 'output':
      processOutput(node)
      break
    case 'condition':
      processCondition(node)
      break
    case 'input':
      processInput(node)
      break
    case 'select':
      processSelect(node)
      break
    case 'calculation':
      processCalculation(node)
      break
    case 'custom':
      processCustom(node)
      break
    default:
      store.commit('ADD_LOG', {
        type: 'warning',
        message: `未知节点类型: ${node.type}`,
        timestamp: new Date().toISOString()
      })
      currentNodeIndex.value++
      processNextNode()
  }
}

const processStart = (node) => {
  // 开始节点通常只是记录日志
  store.commit('ADD_LOG', {
    type: 'info',
    message: `事件流程开始: ${node.description || ''}`,
    timestamp: new Date().toISOString()
  })
  
  currentNodeIndex.value++
  processNextNode()
}

const processEnd = (node) => {
  // 结束节点
  store.commit('ADD_LOG', {
    type: 'success',
    message: `事件流程结束: ${node.description || ''}`,
    timestamp: new Date().toISOString()
  })
  
  finishEvent()
}

const processOutput = (node) => {
  // 输出文本节点
  if (node.content) {
    // 替换内容中的变量引用 ${varName}
    const content = node.content.replace(/\${(\w+)}/g, (match, varName) => {
      return variables.value[varName] !== undefined ? variables.value[varName] : match
    })
    
    store.commit('ADD_LOG', {
      type: 'info',
      message: content,
      timestamp: new Date().toISOString()
    })
  }
  
  // 检查是否有多个分支目标
  if (node.targets && node.targets.length > 0) {
    // 有多个分支，显示分支选择界面
    processMultiBranch(node)
  } else {
    // 没有多分支，继续执行下一个节点
    currentNodeIndex.value++
    processNextNode()
  }
}

// 添加处理多分支节点的函数
const processMultiBranch = (node) => {
  store.commit('ADD_LOG', {
    type: 'info',
    message: `节点有多个分支路径，等待选择...`,
    timestamp: new Date().toISOString()
  })
  
  // 设置交互对象
  currentInteraction.value = {
    type: 'branch',
    prompt: '请选择要继续的分支:',
    options: node.targets.map(target => ({
      label: target.label || `跳转到节点 ${parseInt(target.target) + 1}`,
      value: target.target
    })),
    variableName: null // 分支选择不需要保存变量
  }
  
  // 清空响应
  interactionResponse.value = ''
  
  // 记录日志
  console.log('已设置分支选择交互:', currentInteraction.value)
}

const processCondition = (node) => {
  // 条件判断节点
  try {
    // 准备条件表达式中的变量
    const conditionStr = node.condition.replace(/\${(\w+)}/g, (match, varName) => {
      return variables.value[varName] !== undefined ? JSON.stringify(variables.value[varName]) : 'undefined'
    })
    
    // 计算条件
    // eslint-disable-next-line no-new-func
    const result = new Function('return ' + conditionStr)()
    
    store.commit('ADD_LOG', {
      type: 'info',
      message: `条件判断: ${node.condition} => ${result ? '成立' : '不成立'}`,
      timestamp: new Date().toISOString()
    })
    
    // 根据条件结果跳转
    if (result && node.trueTarget !== undefined && node.trueTarget !== '') {
      const targetIndex = parseInt(node.trueTarget)
      if (!isNaN(targetIndex) && targetIndex >= 0 && targetIndex < event.value.nodes.length) {
        store.commit('ADD_LOG', {
          type: 'info',
          message: `条件为真，跳转到节点 ${targetIndex + 1}: ${event.value.nodes[targetIndex]?.name || '未知节点'}`,
          timestamp: new Date().toISOString()
        })
        currentNodeIndex.value = targetIndex
      } else {
        store.commit('ADD_LOG', {
          type: 'warning',
          message: `条件为真，目标节点索引 ${node.trueTarget} 无效，继续执行下一个节点`,
          timestamp: new Date().toISOString()
        })
        currentNodeIndex.value++
      }
    } else if (!result && node.falseTarget !== undefined && node.falseTarget !== '') {
      const targetIndex = parseInt(node.falseTarget)
      if (!isNaN(targetIndex) && targetIndex >= 0 && targetIndex < event.value.nodes.length) {
        store.commit('ADD_LOG', {
          type: 'info',
          message: `条件为假，跳转到节点 ${targetIndex + 1}: ${event.value.nodes[targetIndex]?.name || '未知节点'}`,
          timestamp: new Date().toISOString()
        })
        currentNodeIndex.value = targetIndex
      } else {
        store.commit('ADD_LOG', {
          type: 'warning',
          message: `条件为假，目标节点索引 ${node.falseTarget} 无效，继续执行下一个节点`,
          timestamp: new Date().toISOString()
        })
        currentNodeIndex.value++
      }
    } else {
      store.commit('ADD_LOG', {
        type: 'info',
        message: `条件${result ? '为真' : '为假'}，未设置跳转目标，继续执行下一个节点`,
        timestamp: new Date().toISOString()
      })
      currentNodeIndex.value++
    }
    
    processNextNode()
  } catch (error) {
    store.commit('ADD_LOG', {
      type: 'error',
      message: `条件判断出错: ${error.message}`,
      timestamp: new Date().toISOString()
    })
    
    // 保存错误日志
    saveErrorLog(`条件判断出错: ${error.message}`);
    
    // 出错后继续执行下一个节点
    currentNodeIndex.value++
    processNextNode()
  }
}

const processInput = (node) => {
  // 用户输入节点
  store.commit('ADD_LOG', {
    type: 'info',
    message: `等待用户输入...`,
    timestamp: new Date().toISOString()
  })
  
  // 确保提示文本包含变量替换
  let processedPrompt = node.prompt || '请输入:'
  
  // 替换提示文本中的变量引用
  processedPrompt = processedPrompt.replace(/\${(\w+)}/g, (match, varName) => {
    return variables.value[varName] !== undefined ? variables.value[varName] : match
  })
  
  // 设置交互对象
  currentInteraction.value = {
    type: 'input',
    prompt: processedPrompt,
    placeholder: node.placeholder || '请在此输入',
    variableName: node.variableName
  }
  
  // 清空响应
  interactionResponse.value = ''
  
  // 记录日志
  console.log('已设置输入交互:', currentInteraction.value)
}

const processSelect = (node) => {
  // 用户选择节点
  store.commit('ADD_LOG', {
    type: 'info',
    message: `等待用户选择...`,
    timestamp: new Date().toISOString()
  })
  
  // 确保提示文本包含变量替换
  let processedPrompt = node.prompt || '请选择:'
  
  // 替换提示文本中的变量引用
  processedPrompt = processedPrompt.replace(/\${(\w+)}/g, (match, varName) => {
    return variables.value[varName] !== undefined ? variables.value[varName] : match
  })
  
  // 设置交互对象
  currentInteraction.value = {
    type: 'select',
    prompt: processedPrompt,
    options: node.options || [],
    variableName: node.variableName
  }
  
  // 清空响应
  interactionResponse.value = ''
  
  // 记录日志
  console.log('已设置选择交互:', currentInteraction.value)
}

const processCalculation = (node) => {
  // 数字计算节点
  try {
    // 记录原始表达式
    store.commit('ADD_LOG', {
      type: 'info',
      message: `计算表达式: ${node.expression}`,
      timestamp: new Date().toISOString()
    })
    
    // 替换表达式中的变量引用
    let expressionWithValues = node.expression
    const variablesUsed = []
    
    // 记录替换过程
    expressionWithValues = node.expression.replace(/\${(\w+)}/g, (match, varName) => {
      if (variables.value[varName] === undefined) {
        store.commit('ADD_LOG', {
          type: 'warning',
          message: `变量 ${varName} 未定义，使用默认值0`,
          timestamp: new Date().toISOString()
        })
        return 0 // 未定义的变量默认为0
      }
      
      // 确保是数字类型
      const value = Number(variables.value[varName])
      variablesUsed.push({ name: varName, value })
      
      if (isNaN(value)) {
        store.commit('ADD_LOG', {
          type: 'warning',
          message: `变量 ${varName} 值 "${variables.value[varName]}" 不是有效数字，使用0代替`,
          timestamp: new Date().toISOString()
        })
        return 0
      }
      
      return value
    })
    
    // 记录使用的变量
    if (variablesUsed.length > 0) {
      store.commit('ADD_LOG', {
        type: 'info',
        message: `使用的变量: ${variablesUsed.map(v => `${v.name}=${v.value}`).join(', ')}`,
        timestamp: new Date().toISOString()
      })
    }
    
    // 记录替换后的表达式
    store.commit('ADD_LOG', {
      type: 'info',
      message: `计算：${expressionWithValues}`,
      timestamp: new Date().toISOString()
    })
    
    // 计算表达式
    // eslint-disable-next-line no-new-func
    const result = Number(new Function('return ' + expressionWithValues)())
    
    store.commit('ADD_LOG', {
      type: 'success',
      message: `计算结果: ${result}`,
      timestamp: new Date().toISOString()
    })
    
    // 如果设置了结果变量名，保存结果
    if (node.resultVariable) {
      // 明确转换为数字类型并保存
      variables.value[node.resultVariable] = Number(result)
      
      store.commit('ADD_LOG', {
        type: 'success',
        message: `结果已保存到变量: ${node.resultVariable} = ${variables.value[node.resultVariable]}`,
        timestamp: new Date().toISOString()
      })
    } else {
      store.commit('ADD_LOG', {
        type: 'warning',
        message: `未设置结果变量名，计算结果未保存`,
        timestamp: new Date().toISOString()
      })
    }
    
    // 继续下一个节点
    currentNodeIndex.value++
    processNextNode()
  } catch (error) {
    store.commit('ADD_LOG', {
      type: 'error',
      message: `计算出错: ${error.message}`,
      timestamp: new Date().toISOString()
    })
    
    // 保存错误日志
    saveErrorLog(`计算出错: ${error.message}`)
    
    // 出错后也继续执行下一个节点
    currentNodeIndex.value++
    processNextNode()
  }
}

const processCustom = async (node) => {
  // 自定义执行节点
  try {
    store.commit('ADD_LOG', {
      type: 'info',
      message: `执行自定义代码节点: ${node.name}`,
      timestamp: new Date().toISOString()
    })
    
    // 准备参数对象
    const params = {}
    if (node.customParams && node.customParams.length > 0) {
      store.commit('ADD_LOG', {
        type: 'info',
        message: `处理参数...`,
        timestamp: new Date().toISOString()
      })
      
      for (const param of node.customParams) {
        let paramValue = param.value
        
        // 替换变量引用
        if (typeof paramValue === 'string') {
          paramValue = paramValue.replace(/\${(\w+)}/g, (match, varName) => {
            if (variables.value[varName] === undefined) {
              store.commit('ADD_LOG', {
                type: 'warning',
                message: `参数 ${param.name} 引用的变量 ${varName} 未定义`,
                timestamp: new Date().toISOString()
              })
              return undefined
            }
            return variables.value[varName]
          })
        }
        
        // 根据参数类型转换
        switch (param.type) {
          case 'number':
            paramValue = Number(paramValue)
            break
          case 'boolean':
            paramValue = Boolean(paramValue === 'true' || paramValue === true)
            break
          case 'object':
            if (typeof paramValue === 'string') {
              try {
                paramValue = JSON.parse(paramValue)
              } catch (e) {
                store.commit('ADD_LOG', {
                  type: 'warning',
                  message: `参数 ${param.name} 的值不是有效的JSON对象: ${e.message}`,
                  timestamp: new Date().toISOString()
                })
                paramValue = {}
              }
            }
            break
          // 字符串类型不需要转换
          default:
            break
        }
        
        params[param.name] = paramValue
        
        store.commit('ADD_LOG', {
          type: 'info',
          message: `参数 ${param.name} = ${JSON.stringify(paramValue)}`,
          timestamp: new Date().toISOString()
        })
      }
    }
    
    // 获取代码
    let functionCode = node.customCode || ''
    
    // 如果有指定自定义节点类型ID，则从已发布的节点类型中获取代码
    if (node.customNodeTypeId) {
      store.commit('ADD_LOG', {
        type: 'info',
        message: `使用自定义节点类型 ID: ${node.customNodeTypeId}`,
        timestamp: new Date().toISOString()
      })
      
      try {
        // 获取已发布的自定义节点类型
        if (!store.state.publishedVersions || store.state.publishedVersions.length === 0) {
          // 加载已发布的自定义节点类型
          await store.dispatch('fetchPublishedVersions')
        }
        
        // 查找对应的节点类型
        const nodeType = store.state.publishedVersions.find(item => item.id === node.customNodeTypeId)
        
        if (nodeType) {
          store.commit('ADD_LOG', {
            type: 'info',
            message: `找到自定义节点类型: ${nodeType.name} v${nodeType.version}`,
            timestamp: new Date().toISOString()
          })
          
          functionCode = nodeType.code
        } else {
          store.commit('ADD_LOG', {
            type: 'error',
            message: `未找到指定的自定义节点类型: ${node.customNodeTypeId}`,
            timestamp: new Date().toISOString()
          })
          throw new Error(`未找到指定的自定义节点类型: ${node.customNodeTypeId}`)
        }
      } catch (error) {
        store.commit('ADD_LOG', {
          type: 'error',
          message: `获取自定义节点类型失败: ${error.message}`,
          timestamp: new Date().toISOString()
        })
        throw error
      }
    }
    
    // 创建可执行的函数代码
    functionCode = functionCode.trim()
    
    // 如果代码不是函数形式，则进行包装
    if (!functionCode.startsWith('function') && !functionCode.includes('=>')) {
      functionCode = `function(params) { ${functionCode} }`
    }
    
    store.commit('ADD_LOG', {
      type: 'info',
      message: `准备执行代码...`,
      timestamp: new Date().toISOString()
    })
    
    // 执行代码
    // eslint-disable-next-line no-new-func
    const customFunction = new Function('return ' + functionCode)()
    
    // 显示正在执行消息
    store.commit('ADD_LOG', {
      type: 'info',
      message: `执行中...`,
      timestamp: new Date().toISOString()
    })
    
    // 执行函数，支持异步
    const result = await Promise.resolve(customFunction(params))
    
    // 记录返回结果
    store.commit('ADD_LOG', {
      type: 'success',
      message: `执行完成，结果: ${JSON.stringify(result)}`,
      timestamp: new Date().toISOString()
    })
    
    // 如果设置了结果变量名，保存结果
    if (node.resultVariable) {
      variables.value[node.resultVariable] = result
      
      store.commit('ADD_LOG', {
        type: 'success',
        message: `结果已保存到变量: ${node.resultVariable} = ${JSON.stringify(result)}`,
        timestamp: new Date().toISOString()
      })
    } else {
      store.commit('ADD_LOG', {
        type: 'warning',
        message: `未设置结果变量名，执行结果未保存`,
        timestamp: new Date().toISOString()
      })
    }
    
    // 继续下一个节点
    currentNodeIndex.value++
    processNextNode()
  } catch (error) {
    store.commit('ADD_LOG', {
      type: 'error',
      message: `自定义代码执行出错: ${error.message}`,
      timestamp: new Date().toISOString()
    })
    
    // 保存错误日志
    await saveErrorLog(`自定义代码执行出错: ${error.message}`)
    
    // 出错后也继续执行下一个节点
    currentNodeIndex.value++
    processNextNode()
  }
}

const submitInteraction = () => {
  if (!currentInteraction.value) return
  
  const { type, variableName } = currentInteraction.value
  
  // 记录交互结果
  if (type === 'branch') {
    // 分支选择
    const selectedTarget = interactionResponse.value
    const targetIndex = parseInt(selectedTarget)
    
    store.commit('ADD_LOG', {
      type: 'info',
      message: `用户选择了分支: ${currentInteraction.value.options.find(opt => opt.value === selectedTarget)?.label || '未知分支'}`,
      timestamp: new Date().toISOString()
    })
    
    // 清除当前交互
    currentInteraction.value = null
    
    // 跳转到目标节点
    if (!isNaN(targetIndex) && targetIndex >= 0 && targetIndex < event.value.nodes.length) {
      store.commit('ADD_LOG', {
        type: 'info',
        message: `跳转到节点 ${targetIndex + 1}: ${event.value.nodes[targetIndex]?.name || '未知节点'}`,
        timestamp: new Date().toISOString()
      })
      currentNodeIndex.value = targetIndex
      processNextNode()
    } else {
      store.commit('ADD_LOG', {
        type: 'warning',
        message: `目标节点索引 ${selectedTarget} 无效，继续执行下一个节点`,
        timestamp: new Date().toISOString()
      })
      currentNodeIndex.value++
      processNextNode()
    }
  } else {
    // 常规输入或选择
    store.commit('ADD_LOG', {
      type: 'info',
      message: `用户${type === 'input' ? '输入' : '选择'}: ${interactionResponse.value}`,
      timestamp: new Date().toISOString()
    })
    
    // 如果有变量名，保存结果到变量
    if (variableName) {
      variables.value[variableName] = interactionResponse.value
    }
    
    // 清除当前交互
    currentInteraction.value = null
    
    // 继续下一个节点
    currentNodeIndex.value++
    processNextNode()
  }
}

const finishEvent = async () => {
  eventFinished.value = true
  
  store.commit('ADD_LOG', {
    type: 'success',
    message: `事件 "${event.value.name}" 执行完成`,
    timestamp: new Date().toISOString()
  })
  
  // 计算运行时长
  const startTime = logs.value.length > 0 ? new Date(logs.value[0].timestamp) : new Date();
  const endTime = new Date();
  const duration = endTime - startTime;
  
  // 准备日志数据
  const logData = {
    eventId: event.value.id,
    runTime: startTime.toISOString(),
    status: 'success', // 可以根据实际情况判断是否成功
    result: '事件执行完成',
    logs: logs.value.map(log => ({
      ...log,
      timestamp: log.timestamp || new Date().toISOString()
    })),
    duration: duration // 运行时长(毫秒)
  };
  
  try {
    // 调用后端API保存日志
    await axios.post('/api/logs', logData);
    console.log('日志保存成功');
  } catch (error) {
    console.error('保存日志失败:', error);
  } finally {
    resetRunningState();
  }
}

// 添加一个保存错误日志的函数
const saveErrorLog = async (errorMessage) => {
  const startTime = logs.value.length > 0 ? new Date(logs.value[0].timestamp) : new Date();
  const endTime = new Date();
  const duration = endTime - startTime;
  
  // 准备日志数据
  const logData = {
    eventId: event.value.id,
    runTime: startTime.toISOString(),
    status: 'error',
    result: errorMessage || '事件执行失败',
    logs: logs.value.map(log => ({
      ...log,
      timestamp: log.timestamp || new Date().toISOString()
    })),
    duration: duration
  };
  
  try {
    // 调用后端API保存日志
    await axios.post('/api/logs', logData);
    console.log('错误日志保存成功');
  } catch (error) {
    console.error('保存错误日志失败:', error);
  } finally {
    resetRunningState();
  }
}

// 重置运行状态
const resetRunningState = () => {
  store.commit('SET_RUNNING', false);
  currentInteraction.value = null;
  eventFinished.value = true;
  
  console.log('事件运行状态已重置');
}

onMounted(() => {
  fetchEvent()
  
  // 加载事件可用变量
  store.dispatch('fetchAllAvailableVariables', route.params.id).then(() => {
    // 初始化变量值
    store.state.allAvailableVariables.forEach(variable => {
      if (variable.defaultValue) {
        try {
          // 尝试解析复杂类型的默认值（如数组、对象）
          let value = variable.defaultValue
          
          if (variable.type === 'number') {
            value = Number(value)
          } else if (variable.type === 'boolean') {
            value = value.toLowerCase() === 'true'
          } else if (['array', 'object'].includes(variable.type)) {
            try {
              value = JSON.parse(value)
            } catch (e) {
              console.warn(`无法解析变量 ${variable.name} 的默认值为 ${variable.type}`)
            }
          }
          
          variables.value[variable.name] = value
        } catch (error) {
          console.error(`设置变量 ${variable.name} 默认值失败:`, error)
          variables.value[variable.name] = variable.defaultValue
        }
      } else {
        // 设置默认的空值
        variables.value[variable.name] = getDefaultEmptyValue(variable.type)
      }
    })
  })
})

// 获取变量类型的默认空值
const getDefaultEmptyValue = (type) => {
  switch (type) {
    case 'string': return ''
    case 'number': return 0
    case 'boolean': return false
    case 'datetime': return new Date().toISOString()
    case 'array': return []
    case 'object': return {}
    default: return null
  }
}
</script>

<style scoped>
.run-card,
.interaction-card,
.variables-card {
  margin-bottom: 20px;
}

.interaction-card {
  border: 2px solid #e6a23c;
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.2);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 4px 12px rgba(230, 162, 60, 0.2);
  }
  50% {
    box-shadow: 0 4px 16px rgba(230, 162, 60, 0.4);
  }
  100% {
    box-shadow: 0 4px 12px rgba(230, 162, 60, 0.2);
  }
}

.log-container {
  height: 300px;
  overflow-y: auto;
  background-color: #303133;
  color: #fff;
  padding: 10px;
  font-family: monospace;
  border-radius: 4px;
}

.log-item {
  margin-bottom: 5px;
  padding: 3px 5px;
  border-left: 3px solid transparent;
}

.log-item.info {
  border-left-color: #909399;
}

.log-item.success {
  border-left-color: #67c23a;
  color: #67c23a;
}

.log-item.warning {
  border-left-color: #e6a23c;
  color: #e6a23c;
}

.log-item.error {
  border-left-color: #f56c6c;
  color: #f56c6c;
}

.empty-log {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.interaction-container {
  padding: 10px;
}

.interaction-prompt {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}

.interaction-input {
  margin-bottom: 10px;
}

.interaction-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}

.interaction-option {
  margin-right: 10px;
  padding: 5px;
}

.debug-info {
  margin-top: 20px;
  padding: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  font-size: 12px;
}

.branch-options {
  border-left: 3px solid #409eff;
  padding-left: 10px;
}

.branch-option {
  margin-bottom: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.3s;
}

.branch-option:hover {
  background-color: #ecf5ff;
}
</style> 